package com.linkage.jz.bankruptcy.fragment.Project;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.CreateAddrActivity;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingActivity;
import com.linkage.jz.bankruptcy.activity.Project.EditManagerUserInfoActivity;
import com.linkage.jz.bankruptcy.activity.Project.ManagerListActivity;
import com.linkage.jz.bankruptcy.activity.Project.ManagerUserDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ManagerUserPermissionActivity;
import com.linkage.jz.bankruptcy.activity.Project.OtherUserDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.SelManagerListActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.AddProxyUserActivity;
import com.linkage.jz.bankruptcy.adapter.ProManagerListViewAdapter;
import com.linkage.jz.bankruptcy.bean.GroupInfo;
import com.linkage.jz.bankruptcy.bean.ManagerBaseUserInfo;
import com.linkage.jz.bankruptcy.bean.ManagerGroupInfo;
import com.linkage.jz.bankruptcy.bean.ManagerUserInfo;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CreateGroupDialog;
import com.linkage.jz.bankruptcy.widget.CreateUserDialog;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.chat.ChatDetailActivity;
import com.linkage.seapeak.activity.message.MultiMessageHistoryActivity;
import com.linkage.seapeak.activity.message.MultiSendActivity;
import com.linkage.seapeak.base.BaseFragment;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.chad.library.adapter.base.listener.SimpleClickListener.TAG;


/**
 * date : 2016/5/24
 * author : lijiawei
 */
public class ProManagerListFrgment extends BaseFragment implements BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener, SwipeRefreshLayout.OnRefreshListener {

    private ProManagerListViewAdapter mAdapter;
    private ArrayList<ManagerUserInfo> mData;
    private RecyclerView mDataRv;
    private TextView law_searchtxt;
    private String mProID;
    private String isOpen;
    private ShapeLoadingDialog shapeLoadingDialog;
    private CreateGroupDialog dialog;

    private CreateUserDialog createUserDialog;

    private String groupid;

    private View menuAction;

    private View ll_nodata;

    private SwipeRefreshLayout swipe;

    public View getMenuAction() {
        return menuAction;
    }

    public void setMenuAction(View menuAction) {
        this.menuAction = menuAction;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_manager_list, container, false);
        mDataRv = (RecyclerView) view.findViewById(R.id.rv_recyclerview_data);
        law_searchtxt = (TextView) view.findViewById(R.id.law_searchtxt);
        swipe = view.findViewById(R.id.swipe);
        ll_nodata = view.findViewById(R.id.ll_nodata);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initRecyclerView(view);
        shapeLoadingDialog = new ShapeLoadingDialog(getActivity());
        Bundle bundle = this.getArguments();//得到从Activity传来的数据

        swipe.setColorSchemeColors(0xff25b6ed, 0xff6dbcdb, 0xfff0b650, 0xffff534e, 0xffbed73d, 0xff04bfbf,
                0xffff530d, 0xff61bc46);
        swipe.setOnRefreshListener(this);

        if (bundle != null) {
            mProID = bundle.getString("proid");
            isOpen = bundle.getString("openAuth");
        }
    }

    private void initRecyclerView(final View view) {
        mDataRv.addItemDecoration(new Divider(getActivity()));

        law_searchtxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyProInfo info = new MyProInfo();
                info.setId(mProID);
                SelManagerListActivity.start(getActivity(),info,isOpen);
            }
        });
//        law_searchtxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//
//            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
//                if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
//                    InputMethodManager imm = (InputMethodManager) view.getContext()
//                            .getSystemService(Context.INPUT_METHOD_SERVICE);
//                    if (imm != null) {
//                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
//                    }
//                    mData.clear();
//                    mAdapter.notifyDataSetChanged();
//                    getData();
//                }
//                return false;
//            }
//
//        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataRv.setLayoutManager(layoutManager);

        mAdapter = new ProManagerListViewAdapter(mDataRv);
        mAdapter.setOnRVItemClickListener(this);
        mAdapter.setOnRVItemLongClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemChildLongClickListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mData = new ArrayList<ManagerUserInfo>();
        mAdapter.setData(mData);
        mDataRv.setAdapter(mAdapter);
    }

    PublicNoticeDialog noticeDialog;
    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        final ManagerUserInfo infoTmp = mData.get(position);
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
            noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getId() == R.id.btn_save_notice) {
                        if (infoTmp.getCurType() == 1) {
                            //删除用户
                            delUser(infoTmp.getId());
                        } else {
                            //删除群组
                            delGroup(infoTmp.getGroup().getId());
                        }
                    }
                    noticeDialog.dismiss();
                }
            }, 1, "提示", "确认删除么？",
                    "取消", "确认");
            noticeDialog.show();
        }

        if (childView.getId() == R.id.iv_email) {
            if (infoTmp.getUser() != null)
                ChatDetailActivity.start(getActivity(), infoTmp.getUser().getId(),
                        infoTmp.getName(), infoTmp.getBankruptcyProjectId());
        }

        if (childView.getId() == R.id.iv_phone) {
            if (infoTmp.getUser() != null || !TextUtils.isEmpty(infoTmp.getUser().getMobile())) {

                final String phone = infoTmp.getUser().getMobile();
                SetPhone(phone);
                noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.ll_close:
                                noticeDialog.dismiss();
                                break;
                            case R.id.btn_chancel_notice:

                                if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_SMS_PERMISSION)){

                                    try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                        Intent intent = new Intent(Intent.ACTION_SENDTO);
                                        Uri data = Uri.parse("smsto:" + phone);
                                        intent.setData(data);
                                        startActivity(intent);

//                                                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
//                                                intent.putExtra("sms_body", message);
//                                                startActivity(intent);

                                    }catch (Exception ex){
                                        ex.printStackTrace();
                                    }
                                }
                                noticeDialog.dismiss();
                                break;

                            case R.id.btn_save_notice:
                                if(!"".equalsIgnoreCase(phone)) {
                                    if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_CALL_PERMISSION)){

                                        try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                            Intent intent = new Intent(Intent.ACTION_CALL);
                                            Uri data = Uri.parse("tel:" + phone);
                                            intent.setData(data);
                                            startActivity(intent);
                                        }catch (Exception ex){
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                                noticeDialog.dismiss();

                                break;
                        }
                    }
                }, 2,phone, phone,"发短信","拨打电话");
                noticeDialog.show();
            } else
                showToast("无法获取号码");
        }

        if (childView.getId() == R.id.tv_item_bgaswipe_edit) {
            if (infoTmp.getCurType() == 1) {
                EditManagerUserInfoActivity.start(getActivity(), infoTmp);
            } else {
                dialog = new CreateGroupDialog(
                        getActivity(), "编辑分组", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.btn_chancel_g:
                                dialog.dismiss();
                                break;
                            case R.id.btn_save_g:
                                String name = dialog.text_name_g.getText().toString().trim();
                                editGroup(infoTmp, name);
                                dialog.dismiss();
                                break;
                        }
                    }
                });
                dialog.show();
            }
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
        }

        if (childView.getId() == R.id.ll_manager && infoTmp.getUser() != null) {
            if("true".equalsIgnoreCase(isOpen)) {
                Intent intent = new Intent(getActivity(), ManagerUserDetailActivity.class);
                intent.putExtra("info", new Gson().toJson(infoTmp));
                getActivity().startActivity(intent);
            }
        }
        if (childView.getId() == R.id.iv_manageuser_add) {
            groupid = infoTmp.getGroup().getId();
            createUserDialog = new CreateUserDialog(getActivity(), onClickListener);
            createUserDialog.show();
        }
    }

    private void editGroup(final ManagerUserInfo info, final String name) {
        Network.getAPIService()
                .editGroup(getUserToken(), info.getGroup().getId(), name)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(null);
                            return;
                        } else {
                            showToast("修改成功", ToastUtil.TOAST_TYPE.SUCCESS);
                            info.getGroup().setName(name);
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        showToast("修改失败");
                    }
                });
    }

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {

            return true;
        }
        if (childView.getId() == R.id.tv_item_bgaswipe_edit) {

            return true;
        }


        return false;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btn_chancel_u:
                    createUserDialog.dismiss();
                    break;
                case R.id.btn_save_u:
                    String name = createUserDialog.text_name_u.getText().toString().trim();
                    String phone = createUserDialog.text_mobile_u.getText().toString().trim();
                    if("".equalsIgnoreCase(name))
                    {
                        showToast("管理成员姓名不能为空",ToastUtil.TOAST_TYPE.WARNING);
                        return;
                    }
                    if("".equalsIgnoreCase(phone))
                    {
                        showToast("手机号不能为空",ToastUtil.TOAST_TYPE.WARNING);
                        return;
                    }
                    addUser(groupid, name, phone);
                    break;

            }
        }
    };


    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {
        ManagerUserInfo model = mAdapter.getItem(position);
        if (model != null) {

            if (model.getCurType() == 1) {
//                Intent intent = new Intent(getActivity(), OtherUserDetailActivity.class);
//                intent.putExtra("info",new Gson().toJson(model));
//                 getActivity().startActivity(intent);
            }
        }
    }

    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "长按了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }


    @Override
    public void onResume() {
        super.onResume();
        getData();
    }


    int sumNum = 0;
    public void getData() {
        getData(null);
    }
    public void getData(String appendId) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        final String title = law_searchtxt.getText().toString().trim();

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("projectId", mProID)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("searchName", title)
                .add("pageNumber", "1")
                .add("pageSize", "100")
                .build();

        String url = Consts.WEBURL_MANAGERSLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipe.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();

                try {
                    JSONObject object = new JSONObject(str);
                    mData.clear();
                    if (object.optInt("code") == 0) {
                        ManagerGroupInfo managerGroupInfo = new Gson().fromJson(object.optString("data"), ManagerGroupInfo.class);
                        ManagerBaseUserInfo.UserAuth auth =new Gson().fromJson(object.optJSONObject("data").optString("auth").toString(), ManagerBaseUserInfo.UserAuth.class);




                        List<ManagerUserInfo> list = new ArrayList<>();
                        sumNum = 0;

                         HashMap<String, ManagerUserInfo> groupTemp = new HashMap<>();
                        for (ManagerGroupInfo.GroupListBean bean : managerGroupInfo.getGroupList()) {
                            for (ManagerUserInfo info : bean.getList()){
                                if (TextUtils.isEmpty(title) && info.getGroup() != null && !groupTemp.containsKey(info.getGroup().getId())) {
                                    info.setCurType(0);
                                    groupTemp.put(info.getGroup().getId(), info);
                                    info.setAddManagementMembers(bean.getAuth().isAddManagementMembers());
                                    list.add(info);
                                }

                                if (info.getUser() != null) {
                                    ManagerUserInfo tempUser;
                                    tempUser = new Gson().fromJson(new Gson().toJson(info), ManagerUserInfo.class);
                                    tempUser.setCurType(1);
                                    if (!TextUtils.isEmpty(appendId) && info.getId().equals(appendId)) {
                                        info.setUserAuth(auth);
                                        getActivity().runOnUiThread(new Runnable() {

                                            @Override
                                            public void run() {
                                                //更新UI
                                                noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        switch (v.getId()) {
                                                            case R.id.ll_close:
                                                            case R.id.btn_chancel_notice:
                                                                noticeDialog.dismiss();
                                                                break;
                                                            case R.id.btn_save_notice:
                                                                ManagerUserPermissionActivity.start(getActivity(), info, true);
                                                                noticeDialog.dismiss();
                                                                break;

                                                        }
                                                    }
                                                }, 1, "提示", "添加成功，请与其联系登录系统",
                                                        "暂不设置", "设置成员权限");
                                                noticeDialog.show();
                                            }
                                        });
                                    }
                                    list.add(tempUser);
                                }
                            }
                        }

                        if (TextUtils.isEmpty(title)) {
                            for (ManagerGroupInfo.GroupCountBean bean : managerGroupInfo.getGroupCount()) {
                                sumNum += bean.getCnt();
                                if (groupTemp.containsKey(bean.getId()))
                                    groupTemp.get(bean.getId()).setGroupnum(bean.getCnt());
                            }
                        }


                        mData.clear();
                        if (managerGroupInfo.getAuth().isOpenAdministratorList())
                            mData.addAll(list);

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                swipe.setRefreshing(false);
                                mAdapter.setOperatingGroup(managerGroupInfo.getAuth().isOperatingGroup());
                                menuAction.setVisibility(managerGroupInfo.getAuth().isOperatingGroup() ? View.VISIBLE : View.GONE);
                                //更新UI
                                ll_nodata.setVisibility(mData.size() == 0 ? View.VISIBLE : View.GONE);

                                mAdapter.notifyDataSetChanged();
                                if (getActivity() instanceof ManagerListActivity) {
                                    ((ManagerListActivity) getActivity()).setTitleNum(
                                            TextUtils.isEmpty(title) ? "管理人团队成员（" + sumNum + "人）" : "管理人团队成员");
                                }
                            }

                        });
                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public void addUser(String groupId, String name, String phone) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)


                .add("projectId", mProID)
                .add("groupId", groupId)
                .add("memberName", name)
                .add("memberMobile", phone)
                .build();

        String url = Consts.WEBURL_ADDMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        showToast("添加失败");
                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                showToast("添加成功", ToastUtil.TOAST_TYPE.SUCCESS);


                                Boolean setMemberPermissions = object.optJSONObject("data").optBoolean("setMemberPermissions");
                                String data = object.optJSONObject("data").optString("id");

                                if (setMemberPermissions)
                                {
                                    getData(data);
                                }else{
                                    showToast("新增成功");
                                    getData();
                                }
                                if (createUserDialog != null) {
                                    createUserDialog.dismiss();
                                }
                            }

                        });
//                        finish();

                    } else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                if ("该成员已经添加到该组,请勿重复添加".equalsIgnoreCase(object.optString("msg"))) {
                                    createUserDialog.tv_have_user.setVisibility(View.VISIBLE);
                                }
                                showToast(object.optString("msg"));
                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            showToast("添加失败");
                        }

                    });
                }
            }
        });
    }


    public void delGroup(String groupId) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)


                .add("groupId", groupId)
                .build();

        String url = Consts.WEBURL_DELETEGROUP;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        showToast("删除失败");
                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("删除成功");
                                getData();
                            }

                        });
//                        finish();

                    } else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("删除失败");
                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            showToast("删除失败");
                        }
                    });
                }
            }
        });
    }


    public void delUser(String userId) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
//        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("managersTeamId", userId)
                .build();

        String url = Consts.WEBURL_DELETEMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        showToast("删除失败");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("删除成功", ToastUtil.TOAST_TYPE.SUCCESS);
                                getData();
                            }

                        });
//                        finish();

                    } else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("删除失败");
                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            showToast("删除失败");
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        getData();
    }
}
